package com.euond.accv.gateway.filter;

import com.euond.accv.gateway.constant.FilterConstants;
import com.euond.accv.gateway.utils.Utils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Error 处理
 */
public class ErrorFilter extends ZuulFilter {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 是否执行run方法
	 */
	@Override
	public boolean shouldFilter() {
		String retCode = (String)RequestContext.getCurrentContext().get("retCode");
		if(StringUtils.isNotBlank(retCode) && retCode.equals("0")) {
			return true;
		}
		return false;
	}

	@Override
	public Object run() {
		logger.info("run Error Filter.....");

		RequestContext ctx = RequestContext.getCurrentContext();

		String resultStr = Utils.resultJson("9909","执行异常,["+ctx.getResponseBody()+"]!");
		ctx.setResponseBody(resultStr);
		ctx.setSendZuulResponse(false);
		ctx.set(FilterConstants.STATUS_CODE,"9909");
		return null;

	}



	/**
	 * 	pre:请求执行之前filter 
		route: 处理请求，进行路由 
		post: 请求处理完成后执行的filter 
		error:出现错误时执行的filter
	 */
	@Override
	public String filterType() {
		return FilterConstants.ERROR_TYPE;
	}

	@Override
	public int filterOrder() {
		return 10;
	}

}
